﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Cnm.Models;

namespace Cnm.Mvc.Web.Ultilities
{
    public class CategoryExtensions
    {
        private CnmDemoEntities dbContext = new CnmDemoEntities();

        /// <summary>
        /// Get category breadcrumb 
        /// </summary>
        /// <param name="category">Category</param>
        /// <param name="showHidden">A value indicating whether to load hidden records</param>
        /// <returns>Category breadcrumb </returns>
        public IList<Category> GetCategoryBreadCrumb(Category category, bool showHidden = false)
        {
            if (category == null)
                throw new ArgumentNullException("category");

            var result = new List<Category>();

            //used to prevent circular references
            var alreadyProcessedCategoryIds = new List<int>() { };

            while (category != null && //not null
                !alreadyProcessedCategoryIds.Contains(category.Id)) //prevent circular references
            {
                result.Add(category);

                alreadyProcessedCategoryIds.Add(category.Id);

                category = dbContext.Categories.FirstOrDefault(p=>p.Id == category.ParentId);
            }
            result.Reverse();
            return result;
        }
    }
}